<template>
    <div class="section">
        <!-- 第一个筛选条件 -->
        <div class="section1">
            <h1>年度Request数量统计（原始数据）</h1>
            <div class="section2">
                <label>年份：</label>
                <input v-model="year" type="number" placeholder="请输入年份" />
  
                <label>月份范围：</label>
                <select v-model="monthRange">
                    <option value="1-6">1-6月</option>
                    <option value="7-12">7-12月</option>
                </select>
  
                <label>项目：</label>
                <select v-model="project">
                    <option value="">请选择项目</option>
                    <option value="Shinny">Shinny</option>
                    <option value="Other">Other</option>
                </select>
  
                <button @click="fetchData">查询</button>
            </div>

            <!-- 第一个图表容器 -->
            <div ref="chart" class="chart-container"></div>    
        </div>

        <!-- 第二个筛选条件和图表 -->
        <div class="section1">
            <h1>月度Request优先级统计（原始数据）</h1>
            <div class="section2">
                <label>年份：</label>
                <input v-model="year2" type="number" placeholder="请输入年份" />

                <label>月份：</label>
                <select v-model="selectedMonth2">
                    <option value="">请选择月份</option>
                    <option v-for="month in months" :key="month" :value="month">{{ month }}月</option>
                </select>

                <label>项目：</label>
                <select v-model="project2">
                    <option value="">请选择项目</option>
                    <option value="Shinny">Shinny</option>
                    <option value="Other">Other</option>
                </select>

                <button @click="fetchData2">查询</button>
            </div>

            <!-- 第二个图表容器 -->
            <div ref="chart2" class="chart-container"></div>
        </div>

        <!-- 第三个筛选条件和图表 -->
        <div class="section1">
            <h1>周度Request统计（原始数据）</h1>
            <div class="section2">
                <label>年份：</label>
                <input v-model="year3" type="number" placeholder="请输入年份" />

                <label>周数：</label>
                <select v-model="selectedWeek">
                    <option value="">请选择周</option>
                    <option v-for="week in weeks" :key="week" :value="week">第{{ week }}周</option>
                </select>

                <label>项目：</label>
                <select v-model="project3">
                    <option value="">请选择项目</option>
                    <option value="Shinny">Shinny</option>
                    <option value="Other">Other</option>
                </select>
                <label>组别：</label>
                <select v-model="assignmentGroup">
                    <option value="">请选择组</option>
                    <option value="Cloud-Administrators-L1">Cloud-Administrators-L1</option>
                    <option value="Cloud-Administrators-L2">Cloud-Administrators-L2</option>
                    <option value="Cloud-Administrators-Tech Lead">Cloud-Administrators-Tech Lead</option>
                    <option value="null">其他</option>
                </select>

                <button @click="fetchData3">查询</button>
            </div>

            <!-- 第三个图表容器 -->
            <div ref="chart3" class="chart-container"></div>
            <div ref="chart4" class="chart-container"></div>
        </div>
    </div>
  </template>
  
  <script>
  import axios from 'axios'; // 引入 axios
  import * as echarts from 'echarts';
  
  export default {
    data() {
        return {
            year: new Date().getFullYear(), // 默认当前年份
            monthRange: '1-6', // 默认1-6月
            project: '', // 项目名称
            year2: new Date().getFullYear(), // 第二个筛选条件的年份
            selectedMonth2: '', // 第二个筛选条件的月份
            project2: '', // 第二个筛选条件的项目名称
            months: Array.from({ length: 12 }, (_, i) => i + 1), // 生成1到12的月份数组
            year3: new Date().getFullYear(), // 第三个筛选条件的年份
            selectedWeek: '', // 第三个筛选条件的周数
            project3: '', // 第三个筛选条件的项目名称
            assignmentGroup: '', // Assignment Group 参数
            weeks: Array.from({ length: 53 }, (_, i) => i + 1), // 生成1到53的周数组
            chart: null, // ECharts实例
            chart2: null, // 第二个ECharts实例
            chart3: null, // 第三个ECharts实例
            chart4: null, // 第四个ECharts实例
        };
    },
    mounted() {
        this.initChart();
        this.initChart2();
        this.initChart3();
        this.initChart4();
        this.fetchData();
    },
    methods: {
        // 初始化图表
        initChart() {
            this.chart = echarts.init(this.$refs.chart);
        },
        // 初始化第二个图表
        initChart2() {
            this.chart2 = echarts.init(this.$refs.chart2);
        },
        // 初始化第三个图表
        initChart3() {
            this.chart3 = echarts.init(this.$refs.chart3);
        },
        // 初始化第四个图表
        initChart4() {
            this.chart4 = echarts.init(this.$refs.chart4);
        },
  
        // 获取数据
        async fetchData() {
            try {
                // 打印请求参数
                console.log('请求参数:', {
                    year: this.year,
                    monthRange: this.monthRange,
                    project: this.project,
                });
  
                // 使用 axios 调用后端 API
                const response = await axios.get('http://localhost:3000/api/requests_stats', {
                    params: {
                        year: this.year,
                        monthRange: this.monthRange,
                        project: this.project,
                    },
                });
  
                // 检查响应状态
                if (response.status !== 200) {
                    console.error('请求失败，状态码:', response.status);
                    alert('请求失败，请检查控制台日志。');
                    return;
                }
  
                const data = response.data.data;
                if (!data || data.length === 0) {
                    console.warn('没有返回数据');
                    alert('没有返回数据');
                    return;
                }
  
                this.renderChart(data); // 将数据传递给图表渲染函数
            } catch (error) {
                console.error('获取数据失败:', error);
                alert('获取数据失败，请检查控制台日志！');
            }
        },
        async fetchData2() {
            try {
                console.log('第二个请求参数:', {
                    year: this.year2,
                    month: this.selectedMonth2,
                    project: this.project2,
                });

                const response = await axios.get('http://localhost:3000/api/requests_stats/monthly/priority', {
                    params: {
                        year: this.year2,
                        month: this.selectedMonth2,
                        project: this.project2,
                    },
                });

                if (response.status !== 200) {
                    console.error('请求失败，状态码:', response.status);
                    alert('请求失败，请检查控制台日志。');
                    return;
                }

                const data = response.data.data;
                if (!data || data.length === 0) {
                    console.warn('没有返回数据');
                    alert('没有返回数据');
                    return;
                }

                this.renderChart2(data);
            } catch (error) {
                console.error('获取第二个数据失败:', error);
                alert('获取第二个数据失败，请检查控制台日志！');
            }
        },

        // 获取第三个和第四个图表的数据
        async fetchData3() {
            try {
                console.log('第三个和第四个请求参数:', {
                    year: this.year3,
                    week: this.selectedWeek,
                    project: this.project3,
                    assignmentGroup: this.assignmentGroup,
                });

                const response = await axios.get('http://localhost:3000/api/requests_stats/weekly', {
                    params: {
                        year: this.year3,
                        week: this.selectedWeek,
                        project: this.project3,
                        assignmentGroup: this.assignmentGroup,
                    },
                });

                if (response.status !== 200) {
                    console.error('请求失败，状态码:', response.status);
                    alert('请求失败，请检查控制台日志。');
                    return;
                }

                const { chart1, chart2 } = response.data; // 获取两个图表的数据

                if (!chart1 || chart1.length === 0) {
                    console.warn('没有返回第三个图表的数据');
                    alert('没有返回第三个图表的数据');
                    return;
                }

                if (!chart2 || chart2.length === 0) {
                    console.warn('没有返回第四个图表的数据');
                    alert('没有返回第四个图表的数据');
                    return;
                }

                this.renderChart3(chart1); // 渲染第三个图表
                this.renderChart4(chart2); // 渲染第四个图表
            } catch (error) {
                console.error('获取第三个和第四个数据失败:', error);
                alert('获取第三个和第四个数据失败，请检查控制台日志！');
            }
        },

        // 渲染图表
        renderChart(data) {
            const months = data.map((item) => `${item.month}月`);
            const total = data.map((item) => item.total);
            const closedComplete = data.map((item) => item.closedComplete);
            const closedInComplete = data.map((item) => item.closedInComplete);
  
            const option = {
                title: {
                    text: '年度请求数量统计（原始数据）',
                    left: 'left', // 标题居左
                    top: '10px', // 标题距离顶部的距离
                    textStyle: {
                        fontSize: 18,
                        fontWeight: 'bold',
                        color: '#333', // 标题颜色
                    },
                },
                tooltip: {
                    trigger: 'axis',
                },
                legend: {
                    data: ['总数量', 'Closed Complete', 'Closed Incomplete'],
                    bottom: '30px', // 将图例位置调整到X轴下方
                    textStyle: {
                        fontSize: 14, // 图例字体大小
                        color: '#333', // 图例字体颜色
                    },
                },
                xAxis: {
                    type: 'category',
                    data: months,
                    axisLine: {
                        lineStyle: {
                            color: '#333', // X轴线颜色
                        },
                    },
                },
                yAxis: {
                    type: 'value',
                    axisLine: {
                        lineStyle: {
                            color: '#333', // Y轴线颜色
                        },
                    },
                },
                series: [
                    {
                        name: '总数量',
                        type: 'bar',
                        data: total,
                        itemStyle: {
                            color: '#4CAF50', // 柱形颜色
                        },
                        label: {
                            show: true, // 显示标签
                            position: 'top', // 标签位置在柱子上方
                            formatter: '{c}', // 显示的内容为数据值
                        },
                    },
                    {
                        name: 'Closed Complete',
                        type: 'bar',
                        data: closedComplete,
                        itemStyle: {
                            color: '#2196F3', // 柱形颜色
                        },
                        label: {
                            show: true, // 显示标签
                            position: 'top', // 标签位置在柱子上方
                            formatter: '{c}', // 显示的内容为数据值
                        },
                    },
                    {
                        name: 'Closed Incomplete',
                        type: 'bar',
                        data: closedInComplete,
                        itemStyle: {
                            color: '#FF9800', // 柱形颜色
                        },
                        label: {
                            show: true, // 显示标签
                            position: 'top', // 标签位置在柱子上方
                            formatter: '{c}', // 显示的内容为数据值
                        },
                    },
                ],
                backgroundColor: '#f9f9f9', // 图表背景颜色
                grid: {
                    top: '60px', // 图表距离顶部的距离
                    bottom: '90px', // 图表距离底部的距离
                    left: '40px', // 图表距离左侧的距离
                    right: '40px', // 图表距离右侧的距离
                },
            };
  
            this.chart.setOption(option);
        },
        // 第二个图表渲染函数
        renderChart2(data) {
            const priorities = ['1 - Critical', '2 - High', '3 - Moderate', '4 - Low'];
            const total = [];
            const closedResolved = [];
            const inProgress = [];

            priorities.forEach((priority) => {
                const priorityData = data[0]?.priorities[priority];
                total.push(priorityData ? priorityData.total : 0);
                closedResolved.push(priorityData ? priorityData.closedResolved : 0);
                inProgress.push(priorityData ? priorityData.inProgress : 0);
            });

            const option = {
                title: {
                    text: '月度Request优先级统计（原始数据）',
                    left: 'left',
                    top: '10px',
                    textStyle: {
                        fontSize: 18,
                        fontWeight: 'bold',
                        color: '#333',
                    },
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'shadow',
                    },
                },
                legend: {
                    data: ['总数量', 'Closed Complete', 'Closed InComplete'],
                    bottom: '30px',
                    textStyle: {
                        fontSize: 14,
                        color: '#333',
                    },
                },
                xAxis: {
                    type: 'category',
                    data: priorities,
                    axisLine: {
                        lineStyle: {
                            color: '#333',
                        },
                    },
                },
                yAxis: {
                    type: 'value',
                    axisLine: {
                        lineStyle: {
                            color: '#333',
                        },
                    },
                },
                series: [
                    {
                        name: '总数量',
                        type: 'bar',
                        data: total,
                        itemStyle: {
                            color: '#4CAF50',
                        },
                        label: {
                            show: true,
                            position: 'top',
                            formatter: '{c}',
                        },
                    },
                    {
                        name: 'Closed Complete',
                        type: 'bar',
                        data: closedResolved,
                        itemStyle: {
                            color: '#2196F3',
                        },
                        label: {
                            show: true,
                            position: 'top',
                            formatter: '{c}',
                        },
                    },
                    {
                        name: 'Closed InComplete',
                        type: 'bar',
                        data: inProgress,
                        itemStyle: {
                            color: '#FF9800',
                        },
                        label: {
                            show: true,
                            position: 'top',
                            formatter: '{c}',
                        },
                    },
                ],
                backgroundColor: '#f9f9f9',
                grid: {
                    top: '60px',
                    bottom: '90px',
                    left: '40px',
                    right: '40px',
                },
            };

            this.chart2.setOption(option);
        },


        // 渲染第三个图表（按周统计）
        renderChart3(data) {
            const priorities = ['1 - Critical', '2 - High', '3 - Moderate', '4 - Low'];
            const total = [];
            const closedResolved = [];
            const inProgress = [];

            priorities.forEach((priority) => {
                const priorityData = data[0]?.priorities[priority];
                total.push(priorityData ? priorityData.total : 0);
                closedResolved.push(priorityData ? priorityData.closedResolved : 0);
                inProgress.push(priorityData ? priorityData.inProgress : 0);
            });

            const option = {
                title: {
                    text: '周度Request优先级统计',
                    left: 'left',
                    top: '10px',
                    textStyle: {
                        fontSize: 18,
                        fontWeight: 'bold',
                        color: '#333',
                    },
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'shadow',
                    },
                },
                legend: {
                    data: ['总数量', 'Closed Complete', 'Closed Incomplete'],
                    bottom: '30px',
                    textStyle: {
                        fontSize: 14,
                        color: '#333',
                    },
                },
                xAxis: {
                    type: 'category',
                    data: priorities,
                    axisLine: {
                        lineStyle: {
                            color: '#333',
                        },
                    },
                },
                yAxis: {
                    type: 'value',
                    axisLine: {
                        lineStyle: {
                            color: '#333',
                        },
                    },
                },
                series: [
                    {
                        name: '总数量',
                        type: 'bar',
                        data: total,
                        itemStyle: {
                            color: '#4CAF50',
                        },
                        label: {
                            show: true,
                            position: 'top',
                            formatter: '{c}',
                        },
                    },
                    {
                        name: 'Closed Complete',
                        type: 'bar',
                        data: closedResolved,
                        itemStyle: {
                            color: '#2196F3',
                        },
                        label: {
                            show: true,
                            position: 'top',
                            formatter: '{c}',
                        },
                    },
                    {
                        name: 'Closed Incomplete',
                        type: 'bar',
                        data: inProgress,
                        itemStyle: {
                            color: '#FF9800',
                        },
                        label: {
                            show: true,
                            position: 'top',
                            formatter: '{c}',
                        },
                    },
                ],
                backgroundColor: '#f9f9f9',
                grid: {
                    top: '60px',
                    bottom: '90px',
                    left: '40px',
                    right: '40px',
                },
            };

            this.chart3.setOption(option);
        },
        // 渲染第四个图表（按 Item 类型统计）
        renderChart4(data) {
            const items = [
                'Onboarding, Provisioning and Decommissioning Request',
                'Project Request',
                'Report Request',
                'Technical and Configuration Request',
            ];
            const total = [];
            const closedResolved = [];
            const inProgress = [];

            items.forEach((item) => {
                const itemData = data[0]?.items[item];
                total.push(itemData ? itemData.total : 0);
                closedResolved.push(itemData ? itemData.closedResolved : 0);
                inProgress.push(itemData ? itemData.inProgress : 0);
            });

            // 简化 X 轴标签
            const simplifiedItems = [
                'Onboard/Provision Request  ',
                'Project Request',
                'Report Request',
                'Tech & Config Request'
            ];

            const option = {
                title: {
                    text: '按 Item 类型分类的请求数据',
                    left: 'left',
                    top: '10px',
                    textStyle: {
                        fontSize: 18,
                        fontWeight: 'bold',
                        color: '#333',
                    },
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'shadow',
                    },
                },
                legend: {
                    data: ['总数量', 'Closed Complete', 'Closed Incomplete'],
                    bottom: '30px',
                    textStyle: {
                        fontSize: 14,
                        color: '#333',
                    },
                },
                xAxis: {
                    type: 'category',
                    data: simplifiedItems,
                    axisLine: {
                        lineStyle: {
                            color: '#333',
                        },
                    },
                },
                yAxis: {
                    type: 'value',
                    axisLine: {
                        lineStyle: {
                            color: '#333',
                        },
                    },
                },
                series: [
                    {
                        name: '总数量',
                        type: 'bar',
                        data: total,
                        itemStyle: {
                            color: '#4CAF50',
                        },
                        label: {
                            show: true,
                            position: 'top',
                            formatter: '{c}',
                        },
                    },
                    {
                        name: 'Closed Complete',
                        type: 'bar',
                        data: closedResolved,
                        itemStyle: {
                            color: '#2196F3',
                        },
                        label: {
                            show: true,
                            position: 'top',
                            formatter: '{c}',
                        },
                    },
                    {
                        name: 'Closed Incomplete',
                        type: 'bar',
                        data: inProgress,
                        itemStyle: {
                            color: '#FF9800',
                        },
                        label: {
                            show: true,
                            position: 'top',
                            formatter: '{c}',
                        },
                    },
                ],
                backgroundColor: '#f9f9f9',
                grid: {
                    top: '60px',
                    bottom: '90px',
                    left: '40px',
                    right: '40px',
                },
            };

            this.chart4.setOption(option);
        },
    },
  };
  </script>
  
<style scoped>
.section {
    position: relative;
    top: 0px;
    overflow-y: auto; /* 启用垂直滚动条 */
    /*text-align: center；*/
}

.section1 {
    font-size: 15px;
    margin-top: 20px;
    margin-bottom: 20px; /* 为每个部分添加底部间距 */
    background-color: white; /* 白色背景 */
    border-radius: 10px; /* 圆角 */
    padding: 20px; /* 内边距 */
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1); /* 添加阴影 */
    text-align: center；
}
.section2 {
    text-align: center；
}

.chart-container {
    width: 100%; /* 设置宽度为100% */
    height: 500px; /* 设置高度为500px */
    padding: 20px; /* 添加内边距以增加空间 */
    box-sizing: border-box; /* 确保内边距不会影响总宽度 */
}

/* 添加一些基本样式以美化界面 */
div {
    margin: 20px;
}

label {
    margin-right: 10px;
}

input[type="number"],
select {
    margin-right: 20px;
    padding: 5px;
    border: 1px solid #ccc;
    border-radius: 4px;
}

button {
    padding: 5px 10px;
    background-color: #007bff;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}

button:hover {
    background-color: #0056b3;
}
</style>